jQuery(document).ready(function($) {
   var addjob=0;
    $.ajaxSetup({cache: false});

    $('.hr_position_set').delegate('.hr_pos_changereq', 'click', function(){
       $(this).children(".hr_comdialogwrap").show();
    });

    $('.hr_position_set').delegate('.hr_pos_changereq', 'mouseleave', function(){
       $(this).children(".hr_comdialogwrap").hide();
    });

   $("#id_state").jobLocation({
     'getcityurl': getcityurl,
     'getprovinceurl': getprovinceurl
   });  

   $(document).on("click", ".addskill", function(){
      var pr = $(this).parents('.req_title');
      var skill = $("input[type='text']", pr).val();
      var skillpr = pr.next();
      var skillmaxerror = skillrepeat = 0;
      $(".control-label b", skillpr).each(function(i){
         var hasskill = $(this).text();
         if(i > 3){
            skillmaxerror = 1;
            return false;
         }
         if(hasskill == skill){
            skillrepeat = 1;
            return false;
         }
      });
      if(skillmaxerror){
         $('.skillerrors').text('最多添加5个技能').show();
         return false;
      }
      if(skillrepeat){
         $('.skillerrors').text('技能添加重复').show();
         return false;
      }
      if(skill.length){
      $('.skillerrors').hide();
      skillpr.append('<div class="control-group">'+
                     '<label class="control-label longwidth" for="" title="'+ (compact_strlen(skill) >= 12 ? skill : '') +'"><b class="longwidth">'+skill+'</b><em>:</em></label>'+
                     '<div class="controls longmarginleft">'+
                     '<select class="exp_select" name="skill_level['+skill+']"><option value=0>--请选择--</option><option value=2>普通</option><option value=3>熟练</option><option value=4>精通</option></select>'+'&nbsp;'+
                     '<input class="required number digits" min="1" name="skill_name['+skill+']" type="text"/><i class="inputword">月</i> <span>以上</span><label for="skill_name['+skill+']" generated="true" class="error" style="display:none;">该项必须填写</label><a href="javascript:;" class="trash"></a>'+
                     '</div></div>');
      }
      $(".req_ctskillbox input", pr).val('').focus();
      $(".set_require_edit .control-group .control-label").tooltip();
      return false;
   });
   
   $(".set_quence_content .control-group .control-label").tooltip();
   $(".set_require_edit .control-group .control-label").tooltip();
   
   $(document).on('keydown', ".req_ctskillbox input", function (e) {
      var key = e.which;
      if (key == 13) {
         $(".addskill").trigger("click");
      }
   });
   
   $(document).on('click', '.trash', function(){
      var pr = $(this).parents('.control-group');
      pr.remove();
      $(".req_ctskillbox input").focus().blur();
   });

   $(document).on("click", "#persontestform .persontesteachone", function(){
      var target = $(this);
      var form = $("#persontestform");
      var items = $("#persontestform .persontesteachone");
      var sheetid = $('.sheetid', target).text();
      var parentdiv = target.parents('.successuploadfile');
      var sheettitle = $('.personname a', target).text();

      if(target.hasClass("selected")){
         $("#persontestbody i.removetest").trigger("click");
      }
      else {
         $("input[name='persontestsheet']", form).val(sheetid);

         $("#persontestform").ajaxSubmit(function() {
            items.removeClass("selected");
            target.addClass("selected");
            $(".set_quence li.cur_li a i").removeClass("nothavedone").addClass("havedone");
            $('.uploadfile_title', parentdiv).empty().html('<b>已选评测：</b><span>' + sheettitle + '</span><i class="removetest"></i>');
            $(document).trigger("showinvite", "persontest");
         })
      }
   })
   
   $(document).on("click", "#persontestbody i.removetest", function(){
      $("input[name='persontestsheet']", "#persontestform").val('');
      $("#persontestform").ajaxSubmit(function() {
         $("#persontestform .persontesteachone").removeClass("selected");
         $(".set_quence li.cur_li a i").removeClass("havedone").addClass("nothavedone");
         $('#persontestbody .uploadfile_title').empty().html('<b></b>请在以下测试中选择一个');
         if($("#persontesthead a i").hasClass("nothavedone") && $("#onlinetesthead a i").hasClass("nothavedone")) {
            $("#invitesetting").hide();
         }
      });
   })
   
   $(document).on('mouseenter', '.persontesteachone', function(){
      var dis = $(window).width() - $(this).offset().left;
      if(dis <= 400){
         $(this).find("#persontext_detail").css("left","-245px");
         $(this).find("#persontext_detail .hr_top5uppoint").css("left","311px");
      }
      else{
         $(this).find("#persontext_detail").css("left","-15px");
         $(this).find("#persontext_detail .hr_top5uppoint").css("left","80px");
      }
      $(this).find("#persontext_detail").show();
   }).on('mouseleave', '.persontesteachone', function(){
      $(this).find("#persontext_detail").hide();
   });
   
   $(document).on('click', '.require_edit a', function(){
      $(this).parents('.set_quence_content').hide();
      $('.set_require_edit').show();
      return false;
   })
   
   $(document).on('click', '.set_require_edit .cancel_edit', function(){
      $('.set_require_edit').hide().siblings('.set_quence_content').show();
      return false;
   })
   
   $(document).on('click', '.settext a', function(){
      $(this).parents('.set_quence_content').hide().siblings('.set_require_edit').show();
      return false;
   });
   
   $(document).on('click', '.uploadfile_title button', function(){
       $("#uploadfile").show().position({
          my:"left top+10",
          at:"left-55 bottom",
          of:$(this)
       });
   });
   
   $(document).on('click', '#uploadfile .closediv', function(){
      $("#uploadfile").removeAttr('style').hide();
   });
   
   $(document).on('click', '#invitefirstok .closediv, #invitefirstok a', function(){
      $("#invitefirstok").remove();
   });
   
   $(document).on('click', '#uploadfilesuccess .closediv', function(){
       $('#uploadfilesuccess').removeAttr('style').hide();
   });
   
   $(document).on("click", "#click_howtoconfig", function(){
      var target = $(this);
      $("#hr_howtoconfig").show().position({
         my:"left top+10",
         at:"left-60 bottom",
         of:target
      });
   });
   
   $(document).on('click', '.closediv', function(){
       $(this).closest('.popup').hide();
   });

   $(document).on('click', 'table.companysheets td i, table.companysheets td span', function(e){
      var target = $(this);
      var pr_td = target.parent();
      var jobid = parseInt($('#job_id').text());
      var onlinetestbody_head = $('.uploadfile_title', target.parents('.successuploadfile'));
      
      $('.server', pr_td).html('').hide();
      if(pr_td.hasClass('selected')){
         // cancel onlinetest
         $.ajax({
            url : canceljobsheet,
            type : "POST",
            data : {jobid: jobid},
            dataType : "json",
            success : function(data){
               if (data.error) {
                  $('.server', pr_td).html(data.error).fadeIn();
               } else {
                  $('#onlinetesthead .havedone').removeClass('havedone').addClass('nothavedone');
                  pr_td.removeClass('selected');
                  onlinetestbody_head.empty().html('<span style="color:#999999;">请在以下试题中选择一个</span>');
               }
            }
         });
      } else {
         // choose onlinetest
         var sheetid = parseInt($('.sheetid', pr_td).text());

         $.ajax({
            url : choosejobsheet,
            type : "POST",
            data : {jobid: jobid, sheetid: sheetid},
            dataType : "json",
            success : function(data){
               if (data.error) {
                  $('.server', pr_td).html(data.error).fadeIn(100, function(){
                     $(this).fadeOut(6000, function(){$(this).html('');});
                  });
               } else {
                  $('td', target.parents('.companysheets')).removeClass('selected');
                  pr_td.addClass('selected');
                  $('#onlinetesthead .nothavedone').removeClass("nothavedone").addClass("havedone");
                  onlinetestbody_head.empty().html('<b>已选试题：</b>').append($('span.sheetname', pr_td).clone()).append('<i class="removetest"></i>');
                  pr_td.append("<span class='savedone' style='position:absolute;margin-left:10px;padding:2px;background:#eff4dc;'>保存成功</span>");
                  $(".savedone", pr_td).fadeOut(3000, function(){$(this).remove()});
                  $(document).trigger("showinvite", "onlinetest");
               }
            }
         });
      }
   });
   
   $(document).on("click", "#onlinetestbody i.removetest", function(){
      var target = $(this);
      var jobid = parseInt($('#job_id').text());
      $.ajax({
         url : canceljobsheet,
         type : "POST",
         data : {jobid: jobid},
         dataType : "json",
         success : function(){
            $('.uploadfile_title', target.parents('.successuploadfile')).empty().html('<span style="color:#999999;">请在以下试题中选择一个</span>');
            $('#onlinetestbody td').removeClass('selected');
            $('#onlinetesthead .havedone').removeClass('havedone').addClass('nothavedone');
            if($("#persontesthead a i").hasClass("nothavedone") && $("#onlinetesthead a i").hasClass("nothavedone")) {
               $("#invitesetting").hide();
            }
         }
      });
   });
   
   $(document).on("mouseenter", ".level_explan", function(){
      $(this).find(".hr_net_tipdialog").show();
   });
   
   $(document).on("mouseleave", ".level_explan",function(){
      $(this).find(".hr_net_tipdialog").hide();
   });
   
   $(document).on("click", "input.auto_invite", function(){
      var target = $(this);
      var jobid = parseInt($('#job_id').text());
      var auto = $(this).prop("checked") ? 1 : 0;
      $("input.auto_invite").not($(this)).prop("checked", $(this).prop("checked"));
      $.ajax({
         type: 'POST',
         url: OC.filePath('jobposition', 'ajax', 'setautoinvite.php'),
         data: {jobid: jobid, auto: auto},
         beforeSend: function() {
            if(!showLoading(target))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if(result.status === 'success') {
               return true;
            } else if(result.error) {
               showMessagePanel(result.error, target, true, {placement:'left'});
            }
         }
      });
   });
   
   // select jobmanager
   $(".selectmanager").on("click", "#selectjobmanager", function() {
      var target = $(this);
      var jobid = parseInt($('#job_id').text());
      $('#jobmanagerlistbody').html('');
      $("#jobmanagerlist").show().position({
         my:"left-43 top",
         at:"left bottom+9",
         of:target
      });
      $.ajax({
         type: 'GET',
         url: OC.filePath('jobposition', 'ajax', 'getjobmanagerlist.php'),
         data: {jobid: jobid},
         cache: false, 
         beforeSend: function(xhr, settings) {
            if(!showLoading($('#jobmanagerlistbody')))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            $('#jobmanagerlistbody').html(result);
         }
      });
   });
   
   var buildAdminName = function(adminUsers) {
      var adminNameArr = new Array();
      $.each(adminUsers,function(i, adminUser) {
         if(i==5) {
            adminNameArr.push('...');
            return false;
         }
         
         adminNameArr.push(adminUser['displayname']);
      });
      
      return adminNameArr.length ? adminNameArr.join('、') : '--';
   }
   
   $("#jobmanagerlist").on("click", ".close", function() {
      $("#jobmanagerlist").hide();
   }).on("click", "td a", function() {
      var target = $(this);
      var uid = $(this).data("uid");
      var jobid = parseInt($('#job_id').text());
      
      if($(this).hasClass("cur_a")) {
         $.ajax({
            type: 'POST',
            url: OC.filePath('jobposition', 'ajax', 'unsetjobmanager.php'),
            data: {jobid: jobid, uid: uid},
            beforeSend: function(xhr, settings) {
               if(!showLoading(target))
                  return false;
            },
            success: function(result){
               if (!isLoggedIn(result, target)) {
                  window.location = redirect_url;
                  return;
               }
               
               if(!$.isPlainObject(result)) {
                  result = $.parseJSON(result);
               }
               
               if(result.status === 'success') {
                  $("#jobmanagername").text(buildAdminName(result.data.adminUsers));
                  target.removeClass("cur_a");
                  $("#jobmanagerlist").position({
                     my:"left-43 top",
                     at:"left bottom+9",
                     of:$("#selectjobmanager")
                  });
               } else if(result.status === 'error') {
                  showMessagePanel(result.data.message, target, true, {placement:'top'});
               }
            }
         });
      } else {
         $.ajax({
            type: 'POST',
            url: OC.filePath('jobposition', 'ajax', 'setjobmanager.php'),
            data: {jobid: jobid, uid: uid},
            beforeSend: function(xhr, settings) {
               if(!showLoading(target))
                  return false;
            },
            success: function(result){
               if (!isLoggedIn(result, target)) {
                  window.location = redirect_url;
                  return;
               }
               
               if(!$.isPlainObject(result)) {
                  result = $.parseJSON(result);
               }
               
               if(result.status === 'success') {
                  $("#jobmanagername").text(buildAdminName(result.data.adminUsers));
                  target.addClass("cur_a");
                  $("#jobmanagerlist").position({
                     my:"left-43 top",
                     at:"left bottom+9",
                     of:$("#selectjobmanager")
                  });
               } else if(result.status === 'error') {
                  showMessagePanel(result.data.message, target, true, {placement:'top'});
               }
            }
         });
      }
   });
 
  $("#edit_job_position").click(function(event, triggerdo){
      var target = $(this);
      var jobid = $('#jobdetails').data('jobid');
      var sources_string = $('#jobdetails').data('sources');
      sources_string = $('#job_position_form').length > 0 ? $('#job_position_form').data('sources') : sources_string;
      var sources = sources_string.split(',');
      var formloaded = $(this).data('formloaded');

      var getposdetail = '';
      if (jobid && sources_string.length > 0) {
         getposdetail = function() {
           $.ajax({
            type: "GET",
            url: OC.filePath('jobposition', 'ajax', 'getposdetail.php'),
            data: {job_id: jobid, sources: sources_string},
            dataType: 'json',
            success: function(result){
               if (!isLoggedIn(result, target)) {
                  window.location = redirect_url;
                  return;
               }
               if(!$.isPlainObject(result)) {
                  result = $.parseJSON(result);
               }
               if(result.status == 'success') {
                  var pdata = result.data; // Positions data
                  for (var i = sources.length - 1; i >= 0; i--) {
                     if(sources[i]=='51job') continue;
                     if (pdata[sources[i]+'_id1'] && pdata[sources[i]+'_id1'].length > 0) {
                        $("#"+sources[i]+"_id_pos_type_html").html(pdata[sources[i]+'_text1']);
                        $("#"+sources[i]+"_id_pos_type").val(pdata[sources[i]+'_id1']).prop('disabled', false);
                        $("#"+sources[i]+"_id_pos_type_text").val(pdata[sources[i]+'_text1']).prop('disabled', false);
                        $("#"+sources[i]+"_pos1_edit").hide();
                        $("#"+sources[i]+"_pos1_show").show();
                        $("#"+sources[i]+"_pos_div1").show();
                     }
                     
                     if (pdata[sources[i]+'_id2'] && pdata[sources[i]+'_id2'].length > 0) {
                        $("#"+sources[i]+"_id_pos_type2_html").html(pdata[sources[i]+'_text2']);
                        $("#"+sources[i]+"_id_pos_type2").val(pdata[sources[i]+'_id2']).prop('disabled', false);
                        $("#"+sources[i]+"_id_pos_type2_text").val(pdata[sources[i]+'_text2']).prop('disabled', false);
                        $("#"+sources[i]+"_pos2_edit").hide();
                        $("#"+sources[i]+"_pos2_show").show();
                        $("#"+sources[i]+"_pos_div2").show();
                     }
                     
                     if(pdata['id_city']<=0 && pdata[sources[i]+'_id_city'] && pdata[sources[i]+'_id_city']>0){
                        $("#"+sources[i]+"_id_city_html").html(pdata[sources[i]+'_city']);
                        $("#"+sources[i]+"_id_city").val(pdata[sources[i]+'_id_city']).prop('disabled', false);
                        $("#"+sources[i]+"_city_text").val(pdata[sources[i]+'_city']).prop('disabled', false);
                        $("#"+sources[i]+"_city_edit").hide();
                        $("#"+sources[i]+"_city_show").show();
                        $("#"+sources[i]+"_city_div").show();                   
                     }else if(pdata['id_city']<=0 && pdata[sources[i]+'_id_city'] && pdata[sources[i]+'_id_city']<=0){
                        $("#"+sources[i]+"_id_city").prop('disabled', false);
                        $("#"+sources[i]+"_city_text").prop('disabled', false);
                        $("#"+sources[i]+"_city_edit").show();
                        $("#"+sources[i]+"_city_show").hide();
                        $("#"+sources[i]+"_city_div").show(); 
                     }

                     if(sources[i] == 'lagou'){
                        $('#'+sources[i]+'_salary_div').show();
                        $('#'+sources[i]+'_salaryrange').prop('disabled', false);
                        $('#'+sources[i]+'_advantage_div').show();
                        $('#'+sources[i]+'_positionadvantage').prop('disabled', false);
                        $('#'+sources[i]+'_address_div').show();
                        $('#'+sources[i]+'_positionaddress').prop('disabled', false);
                     }else if(pdata['id_city']<=0 && pdata[sources[i]+'_id_city'] && pdata[sources[i]+'_id_city']<=0){
                        $('#'+sources[i]+'_advantage_div').hide();
                        $('#'+sources[i]+'_positionadvantage').prop('disabled', true);
                        $('#'+sources[i]+'_salary_div').hide();
                        $('#'+sources[i]+'_salaryrange').prop('disabled', true);
                        $('#'+sources[i]+'_address_div').hide();
                        $('#'+sources[i]+'_positionaddress').prop('disabled', true);
                     }
                     
                  }
               }
            }
           });
         };
      }

      if(formloaded) {
         $("#jobdetails #job_position_info , #jobdetails #edit_job_position , #jobdetails #sync_job_position").hide();
         $("#jobdetails #job_position_edit").show();
      }
      else {
         $.ajax({
            type: "GET",
            url: OC.filePath('jobposition', 'ajax', 'geteditform.php'),
            data: {job_id: jobid},
            beforeSend: function(xhr, settings) {
               showLoading(target, settings, null, {button:true});
            },
            success: function(result){            
               $("#jobdetails").append(result);
               target.data('formloaded', true);
               if($.isFunction(getposdetail)) getposdetail(); 
               if (triggerdo) {
                  $("#syncs_"+triggerdo+" input[type=checkbox]").prop("checked",true);
                  if (triggerdo != '51job') {
                     // Add new source to sources
                     var sindex = sources.indexOf(triggerdo);
                     if (sindex === -1 ) {
                        sources.push(triggerdo);
                        sources_string = sources.join(",");
                        $('#job_position_form').data('sources', sources_string);
                     }
                     if($("#jobpos_id_city").val()<=0){
                        $('#'+triggerdo+'_city_show').hide();
                        $('#'+triggerdo+'_id_city, #'+triggerdo+'_city_text').prop('disabled', false);
                        $('#'+triggerdo+'_city_edit, #'+triggerdo+'_city_div').show();
                     }
                     $('#'+triggerdo+'_pos1_show, #'+triggerdo+'_pos2_show').hide();
                     $('#'+triggerdo+'_id_pos_type, #'+triggerdo+'_id_pos_type_text, #'+triggerdo+'_id_pos_type2, #'+triggerdo+'_id_pos_type2_text, #'+triggerdo+'_salaryrange, #'+triggerdo+'_positionadvantage, #'+triggerdo+'_positionaddress').prop('disabled', false);
                     $('#'+triggerdo+'_pos1_edit, #'+triggerdo+'_pos2_edit, #'+triggerdo+'_pos_div1, #'+triggerdo+'_pos_div2, #'+triggerdo+'_salary_div, #'+triggerdo+'_advantage_div, #'+triggerdo+'_address_div').show();
                  }
               }
               $("#jobdetails #job_position_info , #jobdetails #edit_job_position , #jobdetails #sync_job_position").hide();
               $("#jobdetails #job_position_edit").show();
            }
         });
         
      }
      
   });
             
   var showSyncPopup = function() {
      // check if needs to show popup 
      if($('#popup_syncto').length > 0) {
         addjob = $('#popup_syncto').attr('data-addjob');
         var syncto = $('#popup_syncto').attr('data-syncto').split(','); 
         var first = syncto.shift(); 
         if(syncto.length <= 0)
            $('#popup_syncto').remove(); 
         else 
            $('#popup_syncto').attr('data-syncto', syncto.join(','));
         if(first.length > 0) {
            $('#sync_job_position .account'+first).trigger('click');
         }
      }
   }; 


   $('#sync_job_position').on('click', '.account51job, .accountzhilian, .accountjiancai, .accountlagou',function(){
      if($(this).hasClass('unclick'))
         return false;

      var target = $(this);
      var sync_now = $('#sync_now').length;

      if ($('i', target).attr('class').length <= 0 && sync_now <= 0) {
         $('#edit_job_position').trigger("click", target.data("type"));
         return false;
      }

      var data = {
         type: target.data("type"),
         syncaction: target.data("syncaction"),
         addjob: addjob,
         job_id: $('#post_job_id').val()
      };

      startSync(target.data("type"), data, function() {
         setTimeout(function() { showSyncPopup(); }, 1);
      }, function() { 
         // nothing to track login 
      }, function() {
        // do nothing here
      }); 

      return false;
   });

   $(".synchronousaccount").on('click', '.account51job, .accountzhilian, .accountjiancai, .accountlagou', function() {
      if($(this).hasClass('unclick'))
         return false;
      
      var target = $(this);
      var synctype = target.data("type");
      var syncresult = target.data("result");
      var source = $(this).closest('.synchronousaccount').data('source');
      var jobid = target.data('jobid');
      var setuplink = jobposindex_url+'setup?id='+jobid+'&sconfirm='+synctype+'#jobdetails'
      var synctype_name;
      var tips;
      if(synctype=='51job') {
         synctype_name = '前程无忧';
      } else if(synctype=='zhilian'){
         synctype_name = '智联招聘';
      }else if(synctype=='lagou'){
         synctype_name = '拉勾';
      }else if(synctype=='jiancai'){
         synctype_name = '建筑英才';
      }
      if(source.indexOf(synctype)>=0) {
         if(synctype=='lagou'){
            tips = '推送将在'+synctype_name+'覆盖或激活或重新发布一个职位';
         }else{
            tips = '推送操作将会覆盖该职位在'+synctype_name+'的信息';
         }
         
      } else {
         tips = '推送将在'+synctype_name+'激活或重新发布一个职位';
      }

      // Force user confirm jobposition info
      if (syncresult.length <= 0) {
         tips += "<br /><b>请您确认职位信息是否填写正确</b>";
         showSyncConfirm(tips, function(){
            window.location = setuplink;
         });
         return false;
      }

      showSyncConfirm(tips, function(){
         var data = {
            type: synctype,
            syncaction: target.data("syncaction"),
            job_id: jobid
         }; 

         startSync(target.data("type"), data);
      });

      return false;
   });

   showSyncPopup();
   
   function showSyncConfirm(html, okcallback, cancelcallback)
   {
      var ok = 0;
      if(jQuery("#syncConfirm").length <= 0) {
         jQuery('body').append('<div id="syncConfirm" class="modal hide fade push_confirm">'+
            '<div class="modal-header">'+
              '<button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>'+
              '<h3 id="syncConfirmLabel">&nbsp;</h3>'+
            '</div>'+
            '<div class="modal-body">'+
               '<div class="confirmtext" id="syncConfirmBody"></div>'+
               '<button id="confirmButton" class="btn btn-info">确定</button>'+
            '</div>'+
            '</div>');
      }
      jQuery("#syncConfirmBody").html(html);
      jQuery("#syncConfirm #confirmButton").unbind('click').click(function() {
         ok = 1;         
         jQuery("#syncConfirm").modal('hide');
         if(okcallback) okcallback.call();
      });
      jQuery("#syncConfirm").off('hide').on('hide', function(){
         if(!ok && cancelcallback) cancelcallback.call();
      });
      jQuery("#syncConfirm").modal('show');
   }

   // var switchAdvancedSearch = function(val) {
   //    $.ajax({
   //       type: 'POST',
   //       url: OC.filePath('jobposition', 'ajax', 'switchsearch.php'),
   //       data: {val: val},
   //       dataType: 'json',
   //       success: function(result){
   //          // do nothing
   //       }
   //    });
   // };
   
   // $(".fixed_resume_search").on("click","#highsearch",function(){
   //    var ishidden = $(".highsearch_wrap").is(":hidden");
   //    var searchheight = $(".highsearch_wrap").height()+25;
   //    if(ishidden) {
   //       $(".highsearch_wrap").show();
   //       $(this).addClass("lowsearch");
   //       $("#actioninner_wrap #headerWrap").css("top",114+searchheight+"px");
   //       $("#actioninner_wrap #jobneeds").css("paddingTop",105+searchheight+"px");
   //       switchAdvancedSearch(1);
   //    }
   //    else {
   //       $(".highsearch_wrap").hide();
   //       $(this).removeClass("lowsearch");
   //       $("#actioninner_wrap #headerWrap").css("top",114+"px");
   //       $("#actioninner_wrap #jobneeds").css("paddingTop",105+"px");
   //       switchAdvancedSearch(0);
   //    }
   // });
   
   // $(".highsearch_wrap").on("click",".click_slideup",function(){
   //    $('#highsearch').trigger('click');
   // });
   
   // var jobssearch = $("#jobssearch").val();
   // var highsearch_warp= $(".highsearch_wrap");
   // if(jobssearch==1){
   //    // also need to re-position #actioninner_wrap 
   //    highsearch_warp.hide(); 
   //    $("#highsearch").trigger("click"); 
   // }


   $(document).bind('keydown', function(event) {
      if(event.keyCode == 27) {
         $(".popup").hide();
         return true;
      }
   });

   $(document).bind('mousedown', function(e){
      e = $.event.fix(e);
      var otarget = $(e.target);
      if(otarget.closest(".popup").length>0) {
         if(otarget.hasClass("closediv")) {
            otarget.closest(".popup").hide();
            return true;
         }
         return true;
      }
     
      // close all popup that no need keep and dropdown by open class
      $('.popup').not('.keepopen').hide().closest('.dropdown.open').removeClass('open');
      return true;
   });
   //sort jobposition by publish_date or applied_num
   $('.fixed_resume_search').on('click', '.positionselect a.sort', function() {
      var neworderby = $(this).data('orderby'); 
      var neworderdir = $(this).data('orderdir');
      var orderby = $('#orderBy').val(); 
      var orderdir = $('#orderDir').val();
      $.ajax({
         type: "POST",
         url: OC.filePath('jobposition', 'ajax', 'sortlist.php'),
         data: {neworderby: neworderby, neworderdir: neworderdir, orderby: orderby, orderdir: orderdir},
         success: function(result){
            var url = window.location.href,  
                ts = $.now(),
                ret = url.replace( /([?&])_=[^&]*/, "$1_=" + ts );                
            window.location = ret + ( ( ret === url ) ? ( /\?/.test(url ) ? "&" : "?" ) + "_=" + ts : "" ); 
         }
      })
   });
   
   var jobsmatch=$("#jobsmatch").val();
   var area_checked_length=$("#jobs_advance_seach #area_all").siblings().children("input[type='checkbox']:checked").length;
   var area_checkbox =$("#jobs_advance_seach #area_all").siblings().children("input[type='checkbox']");
   var sync_checked_length=$("#jobs_advance_seach #sync_all").siblings().children("input[type='checkbox']:checked").length;
   var sync_checkbox =$("#jobs_advance_seach #sync_all").siblings().children("input[type='checkbox']");
   var source_checked_length=$("#jobs_advance_seach #source_all").siblings().children("input[type='checkbox']:checked").length;
   var source_checkbox =$("#jobs_advance_seach #source_all").siblings().children("input[type='checkbox']");
   //match condition
   if(jobsmatch =='all'){
      $("#match_check").prop('checked',true).parent().siblings("li[name]").addClass("cur_selected");
   }
   $("#jobs_advance_seach #match_search li span").each(function(){
      if($(this).data('match')==jobsmatch){
         $(this).parent().addClass('cur_selected');
      }
   })
   //if cannot submit search button,default check or selected all
   if($("#isalreadysearch").val()=='undone'){
      $("#jobs_advance_seach input[type='checkbox']").prop('checked',true);
   }else{
      if(area_checked_length==(area_checkbox.length-1)){
         $("#area_check").prop('checked',true);
      }
      if(sync_checked_length==(sync_checkbox.length-1)){
         $("#sync_check").prop('checked',true);
      }
      if(source_checked_length==(source_checkbox.length-1)){
         $("#source_check").prop('checked',true);
      }
   }   

   $("#jobs_advance_seach").on('click',"input[type='checkbox']",function(){
      var p = $(this).closest('ul');
      var allinputs = p.find("input[type='checkbox']").not(function(el) { 
         return $(this).hasClass('checkall'); 
      });
      var allspans = $(this).parent().siblings().children('span');
      if($(this).hasClass("checkall")) {
         if($(this).is(':checked')) {
            allinputs.prop('checked', true);
         }else{
            allinputs.prop('checked', false);
         }
      }else {
         // one of the normal checkbox 
         if($(this).is(':checked')) {
            // find out how many has been checked 
            var checked = p.find("input[type='checkbox']:checked");
            if(allinputs.length == checked.length) {
               p.find("input.checkall").prop("checked", true); 
            } 
         }else {
            p.find("input.checkall").prop("checked", false);
         }
       }  	
   })
   
   $("#jobs_advance_seach").on('click',".selectall",function(){
      var p = $(this).closest('ul');
      var allinputs = p.find("input[type='checkbox']");
      var checkall = $(this).siblings().children("input[type='checkbox'].checkall");
      if(checkall.prop('checked')==true){
         allinputs.prop('checked',false);            
      }else{
         allinputs.prop('checked',true);     
     }
  })
   
  $("#jobs_advance_seach").on('click',"#match_search li",function(){
     if(!$(this).hasClass("cur_selected")){
        $(this).addClass("cur_selected")
     }
     $(this).siblings().removeClass("cur_selected");
     $("#jobsmatch").val($(this).children().data('match'));
  })

   
   $('#folder_dropdown').on('click', '.showlist', function() {
      $('#foldermanage_modal').modal('show');
      $.ajax({
         url: OC.filePath('jobposition', 'ajax', 'getcustomfolderlist.php'),
         data: {searchurl: $('#more_folder').data('searchurl')},
         beforeSend: function(xhr, settings) {
            showLoading($("#foldermanage_body"));
         },
         success: function(data) {
            $("#foldermanage_body").html(data);
         }
      });
   });
   
   $(".synchronousaccount").on("click",".showmoreoffsite",function(){
      var ishidden = $(this).prev().find(".otheroffsite").is(":hidden");
      if(ishidden){
         $(this).find("em").removeClass("down");
         $(this).prev().addClass("slideborder");
         $(this).prev().find(".otheroffsite,.offsitesetting").show();
      }
      else{
         $(this).find("em").addClass("down");
         $(this).prev().removeClass("slideborder");
         $(this).prev().find(".otheroffsite,.offsitesetting").hide();
      }
   });

   $(".jobactions").on("click",".renew,.renew_success,.renew_false",function(){
      var target = $(this);
      var jobid = target.data('jobid');
      if($(this).hasClass('unclick'))
         return false;
      else
         JobList.do_renew(jobid,'renewjobs');
   });

   $("#refreshtip_dialog").on("click",".cancel",function(){
      $("#refreshtip_dialog").modal('hide');
   });
   
   $("#refreshtip_dialog").on("click",".btn-info",function(){
      $("#refreshtip_dialog").modal('hide');
      showRenewSyncPopup(function() {
         $("#jobposition_renewform").ajaxSubmit(function(result) {
            if(result.success.stat && result.success.stat == 'success'){
               if(result.success.data.length > 0){
                  OC.Notification.showHtml('职位本地刷新成功，页面重载后会显示排序结果'+'<span class="undo tclose">关闭</span>', 10000);
                  $.each(result.success.data,function(index,data) {
                     var title = $('.renew,.renew_success,.renew_false').filterAttr('data-jobid',data.id).data('original-title');
                     var arr = title.split('<br>');
                     arr[0] = "本地刷新时间："+data.renew;
                     var renew_title = arr.join('<br>');
                     $('.renew,.renew_success,.renew_false').filterAttr('data-jobid',data.id).removeClass().addClass('action renew_success').attr('data-original-title',renew_title);
                  });
               }else{
                  OC.Notification.showHtml('刷新失败，请您稍后重试'+'<span class="undo tclose">关闭</span>', 10000);
               }
            }else{
               OC.Notification.showHtml('刷新失败，请您稍后重试'+'<span class="undo tclose">关闭</span>', 10000);
            }
         });
      });
   });

   var showRenewSyncPopup = function(callback) {
      if($('#renew_syncto').length > 0) {
         var syncto = $('#renew_syncto').data('syncto');

         if(syncto.length <= 0) {
            if(callback) callback();
         }else{
            syncto =  syncto.split(',');
            var source = syncto.shift();
            $('#renew_syncto').data('syncto', syncto.join(','));
            var jobids = $('input[name="jobids_'+source+'"]').val().split(',');
            var data = {
                  type: source,
                  syncaction: 'renewjobs',
                  jobids: jobids
                };
            startSync(source, data, function() {
               setTimeout(function() { showRenewSyncPopup(callback); }, 1);
            }, function() { 
               // nothing to track login 
            }, function() {
               // Do nothing here
            });
         }
      }
   };

   $(document).on('click', 'input.renewjob', function(){
      var syncto = $('#renew_syncto').data('syncto');
      if(syncto.length > 0)
         syncto = syncto.split(',');
      else
         syncto = [];
      if($(this).prop('checked')) {
         if(syncto.indexOf($(this).data('source'))<0)
            syncto.push($(this).data('source'));
      }else{
         var i = syncto.indexOf($(this).data('source'));
         if(i >= 0)
            syncto.splice(i,1)
      }
      $('#renew_syncto').data('syncto', syncto.join(','));
   });

   $(document).on('click', '.hr_resumerequiredtip', function(){
      return false;
   });
});

function showJobTrashConfirm(okcallback, cancelcallback) {
   var ok = 0;
   $('#jobTrashConfirm .confirm').unbind('click').click(function() {
      ok = 1;
      if(okcallback) okcallback.call();
      if($('#jobTrashConfirm .noshow').prop('checked')) {
         storageSet('iknow_jobtrash_tips', 1);
      }
      $('#jobTrashConfirm').modal('hide');
   });
   $('#jobTrashConfirm').off('hide').on('hide', function(){
      if(!ok && cancelcallback) cancelcallback.call();
   });
   $('#jobTrashConfirm').modal('show');
}
